class Solution(object):
    def findDistance(self, root, p, q):
        if p == q:
            return 0

        def dfs(node):
            left_val = 0
            right_val = 0
            if node.left:
                left_val = dfs(node.left)
            if node.right:
                right_val = dfs(node.right)
            if left_val:
                if right_val:
                    self.dist = left_val + right_val
                    return 0
                else:
                    if node.val == p or node.val == q:
                        self.dist = left_val
                        return 0
                    else:
                        return left_val + 1
            else:
                if right_val:
                    if node.val == p or node.val == q:
                        self.dist = right_val
                        return 0
                    else:
                        return right_val + 1
                else:
                    if node.val == p or node.val == q:
                        return 1
                    else:
                        return 0
        dfs(root)
        return self.dist